package com.hqyj.javaSpringBoot.modules.common.service.impl;

import com.hqyj.javaSpringBoot.config.ResourcesConfigerBean;
import com.hqyj.javaSpringBoot.modules.common.entity.ImageType;
import com.hqyj.javaSpringBoot.modules.common.entity.Result;
import com.hqyj.javaSpringBoot.modules.common.service.ImageService;
import com.hqyj.javaSpringBoot.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ResourcesConfigerBean configerBean;
    @Value("${artifactId}")
    private String artifactId;

    @Override
    public Result<String> uploadImage(MultipartFile file, String imageType) {
        //判断文件是否为空
        if (file.isEmpty()){
            return new Result<>(Result.ResultCode.failed.code,"Image is null");
        }
        //判断文件是否为图片
        if (!FileUtil.isImage(file)){
            return new Result<>(Result.ResultCode.failed.code,"File is not image");
        }
        //获取图片类型枚举对象
        ImageType imageTypeMenu=ImageType.getImageTypeByName(imageType);
        //构建目标对象绝对地址-----f:/upload/+artifactId+ImageType+图片名字

        String imageName=String.format("%s.%s",System.currentTimeMillis(),
                FileUtil.getFileType(file.getOriginalFilename()));

        String destFolder=String.format("%s%s/%s",System.getProperty("os.name").toLowerCase().startsWith("win")?
                configerBean.getWindowsLocation():configerBean.getLinuxLocation(),
                artifactId,imageType);
        File destFolderFile= new File(destFolder);
        if (!destFolderFile.exists()){
            destFolderFile.mkdirs();
        }
        String absolutePath=String.format("%s/%s",
                destFolder,
                imageName);
        //构建目标对象相对地址-------/upload/+artifactId+ImageType+图片名字
       String relatePath=String.format("%s%s/%s/%s",
               configerBean.getPath(),
               artifactId,imageType,imageName);
         //邪恶图片到目标地址

        try {
            File destFile=new File(absolutePath);
            file.transferTo(destFile);
            //变更图片尺寸------可选
            FileUtil.changeImageSize(absolutePath,absolutePath,
                    imageTypeMenu.length,imageTypeMenu.height);
            //返回result对象
            return new Result<>(Result.ResultCode.success.code,
                    "Upload image success.",relatePath);

        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.ResultCode.failed.code,
                    "Upload image failed.");
        }


    }
}
